using System;
using System.Messaging;

namespace ScottLane.VideoInbox
{
    /// <summary>
    /// A wrapper for the download message queue that provides the ability for Media Center
    /// to download videos and playlists by using their manifest files.
    /// </summary>
    public class DownloadQueue
    {
        private readonly string queuePath = @".\Private$\Video Inbox Downloads";
        private MessageQueue queue;

        /// <summary>
        /// Initializes a new instance of the DownloadQueue class.
        /// </summary>
        public DownloadQueue()
        {
            if (MessageQueue.Exists(queuePath))
            {
                queue = new MessageQueue(queuePath);
            }
            else
            {
                queue = MessageQueue.Create(queuePath, false);
            }
        }

        /// <summary>
        /// Adds a manifest to the back of the queue.
        /// </summary>
        /// <param name="manifest">The manifest.</param>
        public void Add(DownloadManifest manifest)
        {
            queue.Send(manifest);
        }
        
        /// <summary>
        /// Removes a manifest from the front of the queue. 
        /// </summary>
        /// <returns>The manifest.</returns>
        public DownloadManifest Remove()
        {
            DownloadManifest manifest = Peek();

            if (manifest != null)
            {
                Message message = queue.Receive(TimeSpan.Zero);
                manifest = (DownloadManifest)message.Body;
            }

            return manifest;
        }

        /// <summary>
        /// Peeks at the manifest at the front of the queue without removing it.
        /// </summary>
        /// <returns>The manifest.</returns>
        public DownloadManifest Peek()
        {
            DownloadManifest manifest = null;
            Message message = queue.Peek(TimeSpan.Zero);

            if (message != null)
            {
                manifest = (DownloadManifest)message.Body;
            }

            return manifest;
        }
    }
}
